/*Scala code license:

 Copyright 2009/10 Osman Pub

 Licensed under the Apache License, Version 2.0 (the "License") you may not use
 this file except in compliance with the License.

 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for the
 specific language governing permissions and limitations under the License.

 */
/**
 Orginal java code credits:
 * @author Jeff Kirby
 */
package demos

import common._
import java.awt.event._
import javax.media.opengl._
import javax.media.opengl.glu.GLU
import javax.swing._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.io.Source

object Lesson10 {
  def main(args: Array[String]) {
    val glDisplay = GLDisplay(
      "Lesson 10: Loading and moving through a 3D world")
    glDisplay addGLEventListener(new Renderer)
    glDisplay addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent) =
        response = e getKeyCode match {
          case KeyEvent.VK_PAGE_UP => Action lookUp
          case KeyEvent.VK_PAGE_DOWN => Action lookDown
          case KeyEvent.VK_UP => Action stepForward
          case KeyEvent.VK_DOWN => Action stepBackward
          case KeyEvent.VK_RIGHT => Action turnRight
          case KeyEvent.VK_LEFT => Action turnLeft
          case _ => Action none
        }

      override def keyReleased(e: KeyEvent) =
        e getKeyCode match {
          case KeyEvent.VK_ESCAPE => glDisplay stop
          case KeyEvent.VK_B => response = Action blending
          case KeyEvent.VK_F => response = Action filter
          case _ => response = Action none
        }
    })
    glDisplay start
  }

  object Action extends Enumeration { 
    val blending, filter, none, lookDown, lookUp,  stepBackward, stepForward,
    turnLeft, turnRight = Value
  }
  private var response = Action none

  private class Renderer extends GLEventListener {
    /** Called by the drawable to initiate OpenGL rendering by the client.
     * After all GLEventListeners have been notified of a display event, the
     * drawable will swap its buffers if necessary.
     * @param gLDrawable The GLAutoDrawable object.
     */
    private val glu = new GLU
    private val textures = new Array[Int](3)

    private var blending = false
    private var filter = 0
    private var angle, lookUpdown, walkBias, x, z, yrot = 0.0f
    private var sector: Sector = _

    def display(glDrawable: GLAutoDrawable) {
      def update {
        response match {
          case Action.blending => blending = !blending
          case Action.filter => filter = (filter + 1) % textures.length
          case Action.lookDown => lookUpdown += 1
          case Action.lookUp => lookUpdown -= 1

          case Action.stepBackward =>
            x += scala.math.sin(yrot * scala.math.Pi / 180).asInstanceOf[Float] * 0.05f
            z += scala.math.cos(yrot * scala.math.Pi / 180).asInstanceOf[Float] * 0.05f
            if(angle <= 1) angle = 359 else angle -= 10
            walkBias = scala.math.sin(angle * scala.math.Pi / 180).asInstanceOf[Float] / 20

          case Action.stepForward =>
            x -= scala.math.sin(yrot* scala.math.Pi / 180).asInstanceOf[Float] * 0.05f
            z -= scala.math.cos(yrot * scala.math.Pi / 180).asInstanceOf[Float] * 0.05f
            if(angle >= 359) angle = 0 else angle += 10
            walkBias = scala.math.sin(angle * scala.math.Pi / 180).asInstanceOf[Float] / 20

          case Action.turnLeft => yrot += 1
          case Action.turnRight => yrot -= 1
          case _ =>
        }
        response = Action none
      }

      val gl = glDrawable.getGL
      gl glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

      gl glLoadIdentity;									// Reset The View;

      if(blending) { gl glEnable(GL GL_BLEND); gl glDisable(GL GL_DEPTH_TEST)	}
      else { gl glDisable(GL GL_BLEND); gl glEnable(GL GL_DEPTH_TEST) }

      gl glRotatef(lookUpdown, 1, 0, 0)
      gl glRotatef(360 - yrot, 0, 1, 0)

      gl glTranslatef(-x, -walkBias - 0.25f, -z)
      gl glBindTexture(GL GL_TEXTURE_2D, textures(filter))

        // Process Each Triangle
        for( i <- 0 until sector.n) {
          gl glBegin(GL GL_TRIANGLES)
          gl glNormal3f(0, 0, 1)

          for(v <- 0 until 3) {
            gl glTexCoord2f(sector.triangles(i)(v).u, sector.triangles(i)(v).v)
            gl glVertex3f(sector.triangles(i)(v).x, sector.triangles(i)(v).y,
                          sector.triangles(i)(v).z)
          }

          gl glEnd()
      }

      if(response != Action.none) update
    }

    /** Called when the display mode has been changed.  <B>!!
     *CURRENTLY UNIMPLEMENTED IN JOGL !!</B>
     * @param gLDrawable The GLAutoDrawable object.
     * @param modeChanged Indicates if the video mode has changed.
     * @param deviceChanged Indicates if the video device has changed.
     */
    def displayChanged(glDrawable: GLAutoDrawable, modeChanged: Boolean,
                       deviceChanged: Boolean) {}

    /** Called by the drawable immediately after the OpenGL context is
     * initialized for the first time. Can be used to perform one-time OpenGL
     * initialization such as setup of lights and display lists.
     * @param gLDrawable The GLAutoDrawable object.
     */
    def init(glDrawable: GLAutoDrawable) {
      val gl = glDrawable.getGL

      def loadGLTextures {
        val textImg = TextureReader.readTexture("demos/data/images/mud.png")

        //Create Nearest Filtered Texture
        gl glGenTextures(3, textures, 0)

        gl glBindTexture(GL GL_TEXTURE_2D, textures(0))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_NEAREST)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_NEAREST)
        gl glTexImage2D(GL GL_TEXTURE_2D, 0, 3, textImg.width, textImg.height,
                        0, GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg.pixels)

        gl glBindTexture(GL GL_TEXTURE_2D, textures(1))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_LINEAR)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_LINEAR)
        gl glTexImage2D(GL GL_TEXTURE_2D, 0, 3, textImg.width, textImg.height,
                        0, GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg.pixels)

        gl glBindTexture(GL GL_TEXTURE_2D, textures(2))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_LINEAR)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_LINEAR_MIPMAP_NEAREST)
        gl glTexImage2D(GL GL_TEXTURE_2D, 0, 3, textImg.width, textImg.height,
                        0, GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg.pixels)
      }

      def setupWorld {
        val lines = new ListBuffer[String]
        val url = getClass getClassLoader() getResource(
          "demos/data/models/world.txt")
        lines ++= Source.fromURL(url).getLines filter { l =>
          !(l.trim.length == 0 || l.startsWith("//")) }

        val l = lines find { _ startsWith "NUMPOLLIES" }
        if(l isDefined) {
          val num = (l.get drop "NUMPOLLIES".length).trim.toInt
          sector = new Sector(num); lines -= l.get
        }
        for(i <- 0 until sector.n) for(v <- 0 until 3) {
          val l = lines(i * 3 + v)
          val st = new StringTokenizer(l, " ")

          sector.triangles(i)(v).x = (st.nextToken).toFloat
          sector.triangles(i)(v).y = (st.nextToken).toFloat
          sector.triangles(i)(v).z = (st.nextToken).toFloat
          sector.triangles(i)(v).u = (st.nextToken).toFloat
          sector.triangles(i)(v).v = (st.nextToken).toFloat
        }
      }

      // init
      gl glShadeModel(GL GL_SMOOTH)               // Enable Smooth Shading
      gl glClearColor(0, 0, 0, 0)     // Black Background
      gl glClearDepth(1)                       // Depth Buffer Setup
      gl glHint(GL GL_PERSPECTIVE_CORRECTION_HINT, GL GL_NICEST) 
      gl glEnable(GL GL_TEXTURE_2D)
      gl glBlendFunc(GL GL_SRC_ALPHA, GL GL_ONE)                  
      gl glEnable(GL GL_BLEND)
      gl glEnable(GL GL_DEPTH_TEST)                            
      gl glDepthFunc(GL GL_LEQUAL)                            

      loadGLTextures; setupWorld
    }

    /** Called by the drawable during the first repaint after the component has
     * been resized. The client can update the viewport and view volume of the
     * window appropriately, for example by a call to
     * GL.glViewport(int, int, int, int) note that for convenience the component
     * has already called GL.glViewport(int, int, int, int)(x, y, width, height)
     * when this method is called, so the client may not have to do anything in
     * this method.
     * @param gLDrawable The GLAutoDrawable object.
     * @param x The X Coordinate of the viewport rectangle.
     * @param y The Y coordinate of the viewport rectanble.
     * @param width The new width of the window.
     * @param height The new height of the window.
     */
    def reshape(glDrawable: GLAutoDrawable, x: Int, y: Int, width: Int,
                height: Int) {
      require(height != 0)

      val gl = glDrawable.getGL
      val h = width.asInstanceOf[Float] / height.asInstanceOf[Float]

      gl glViewport(0, 0, width, height)
      gl glMatrixMode(GL GL_PROJECTION)
      gl glLoadIdentity

      glu gluPerspective(45, h, 0.1, 100)
      gl glMatrixMode(GL GL_MODELVIEW)
      gl glLoadIdentity
    }

    private class Vertex(var u: Float = 0, var v: Float = 0, var x: Float = 0,
                         var y: Float = 0, var z: Float = 0)
    private class Sector(var n: Int) {
      val triangles = Array.ofDim[Vertex](n, 3)
      for(i <- 0 until n) 
        triangles(i) = Array(new Vertex, new Vertex, new Vertex)
    }
  }
}